package com.tust.androidbbsclient;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.tust.androidbbsclient.adapter.PersonArtListRecyclerAdapter;
import com.tust.androidbbsclient.tool.Tool;
import com.tust.androidbbsclient.trans.ArticleList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class VisitorActivity extends AppCompatActivity {
    private Toast toast;
    private int visitorUID;
    int visitorUfavorPrivacy;
    int visitorUcollPrivacy;
    private List<ArticleList> articleLists;//贴文列表不包括贴文内容和图片

    LinearLayout linearLayoutVisitorFavorList;
    LinearLayout linearLayoutVisitorCollList;
    TextView textViewVisitorUname;
    TextView textViewVisitorUgender;
    TextView textViewVisitorUint;
    RecyclerView recyclerViewVisitorArtList;
    PersonArtListRecyclerAdapter visitorArtListRecyclerAdapter;

    //用于在线程间传递消息
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);//获取子线程传递的消息
            if (msg.what == 1) {//查询用户请求返回值
                String strMsg = msg.obj.toString();
                System.out.println("用户信息：" + strMsg);

                if (strMsg.equals("serverFalse")) showToast(Tool.addEmoji() + "服务器通信失败！");
                else {
                    //解析JSON字符串
                    try {
                        JSONArray jsonArray = new JSONArray(strMsg);
                        textViewVisitorUname.setText(jsonArray.getJSONObject(0).getString("uname"));
                        textViewVisitorUgender.setText(jsonArray.getJSONObject(0).getString("ugender"));
                        textViewVisitorUint.setText(jsonArray.getJSONObject(0).getString("uint"));
                        visitorUfavorPrivacy = Integer.parseInt(jsonArray.getJSONObject(0).getString("ufavorPrivacy"));
                        visitorUcollPrivacy = Integer.parseInt(jsonArray.getJSONObject(0).getString("ucollPrivacy"));
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }

                    if (visitorUfavorPrivacy == 1) linearLayoutVisitorFavorList.setVisibility(View.GONE);//设置为不可见，不占用原来的布局空间
                    if (visitorUcollPrivacy == 1) linearLayoutVisitorCollList.setVisibility(View.GONE);
                }
            } else if (msg.what == 2) {//获取用户点赞量请求返回值
                String strMsg = msg.obj.toString();
                System.out.println("点赞量：" + strMsg);

                if (strMsg.equals("serverFalse")) showToast(Tool.addEmoji() + "服务器通信失败！");
                else {
                    TextView textViewPersonUfavorNum = findViewById(R.id.tv_visitorUfavorNum);
                    textViewPersonUfavorNum.setText(strMsg);
                }
            } else if (msg.what == 3) {//获取用户收藏量请求返回值
                String strMsg = msg.obj.toString();
                System.out.println("收藏量：" + strMsg);

                if (strMsg.equals("serverFalse")) showToast(Tool.addEmoji() + "服务器通信失败！");
                else {
                    TextView textViewPersonUcollNum = findViewById(R.id.tv_visitorUcollNum);
                    textViewPersonUcollNum.setText(strMsg);
                }
            } else if (msg.what == 4) {//查询所有贴文列表请求返回值
                String strMsg = msg.obj.toString();
                System.out.println("访客空间查询贴文列表：" + strMsg);

                if (strMsg.equals("serverFalse")) showToast(Tool.addEmoji() + "服务器通信失败！");
                else setRecyclerView(strMsg);//调用RecyclerView设置方法
            } else if (msg.what == 5) {//分页下一页请求返回值
                String strMsg = msg.obj.toString();
                //System.out.println("分页下一页：" + strMsg);

                if (strMsg.equals("serverFalse")) showToast(Tool.addEmoji() + "服务器通信失败！");
                else addRecyclerViewItem(strMsg);//调用RecyclerView设置方法
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_visitor);

        linearLayoutVisitorFavorList = this.findViewById(R.id.ll_visitorFavorList);
        linearLayoutVisitorCollList = this.findViewById(R.id.ll_visitorCollList);
        recyclerViewVisitorArtList = this.findViewById(R.id.rv_visitorArtList);
        textViewVisitorUname = this.findViewById(R.id.tv_visitorUname);
        textViewVisitorUgender = this.findViewById(R.id.tv_visitorUgender);
        textViewVisitorUint = this.findViewById(R.id.tv_visitorUint);
        FloatingActionButton floatingActionButtonVisitorArtList = this.findViewById(R.id.fab_visitorArtList);

        //从意图中获得用户ID
        visitorUID = this.getIntent().getIntExtra("UID", -1);

        //发送查询用户请求子线程
        new Thread() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                BufferedReader bufferedReader = null;
                String data = "";
                try {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 1;//增加handlerMsg标识符

                    URL url = new URL(Tool.InetAddress + "/selectUname.do");//请求地址
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //连接类相关设置
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(3000);//连接服务器超时
                    connection.setReadTimeout(3000);//从服务器读取数据超时
                    connection.setDoInput(true);//允许写入，从服务端读取结果流
                    connection.setDoOutput(true);//允许写出，开启Post请求体
                    connection.setUseCaches(false);//不使用Cache
                    connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                    connection.connect();//连接网络
                    String params = "UID=" + visitorUID;//请求体内容
                    outputStream = connection.getOutputStream();//请求输出流
                    outputStream.write(params.getBytes());

                    int code = connection.getResponseCode();//获得响应状态码
                    if (code == 200) {//返回状态码200，连接成功
                        bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        data = bufferedReader.readLine();

                        handlerMsg.obj = data;//写入线程传递消息
                    } else handlerMsg.obj = "serverFalse";//服务器通信失败
                    connection.disconnect();//关闭连接

                    handler.sendMessage(handlerMsg);//发送线程消息
                } catch (IOException e) {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 1;//增加handlerMsg标识符
                    handlerMsg.obj = "serverFalse";
                    handler.sendMessage(handlerMsg);

                    //throw new RuntimeException(e);
                } finally {
                    try {
                        if (bufferedReader != null) bufferedReader.close();
                        if (outputStream != null) {
                            outputStream.flush();
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        System.out.println("子线程：finally失败");
                        //throw new RuntimeException(e);
                    }
                }
            }
        }.start();

        //发送获取用户点赞量请求子线程
        new Thread() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                BufferedReader bufferedReader = null;
                String data = "";
                try {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 2;//增加handlerMsg标识符

                    URL url = new URL(Tool.InetAddress + "/getUfavorNum.do");//请求地址
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //连接类相关设置
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(3000);//连接服务器超时
                    connection.setReadTimeout(3000);//从服务器读取数据超时
                    connection.setDoInput(true);//允许写入，从服务端读取结果流
                    connection.setDoOutput(true);//允许写出，开启Post请求体
                    connection.setUseCaches(false);//不使用Cache
                    connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                    connection.connect();//连接网络
                    String params = "UID=" + visitorUID;//请求体内容
                    outputStream = connection.getOutputStream();//请求输出流
                    outputStream.write(params.getBytes());

                    int code = connection.getResponseCode();//获得响应状态码
                    if (code == 200) {//返回状态码200，连接成功
                        bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        data = bufferedReader.readLine();

                        handlerMsg.obj = data;//写入线程传递消息
                    } else handlerMsg.obj = "serverFalse";//服务器通信失败
                    connection.disconnect();//关闭连接

                    handler.sendMessage(handlerMsg);//发送线程消息
                } catch (IOException e) {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 2;//增加handlerMsg标识符
                    handlerMsg.obj = "serverFalse";
                    handler.sendMessage(handlerMsg);

                    //throw new RuntimeException(e);
                } finally {
                    try {
                        if (bufferedReader != null) bufferedReader.close();
                        if (outputStream != null) {
                            outputStream.flush();
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        System.out.println("子线程：finally失败");
                        //throw new RuntimeException(e);
                    }
                }
            }
        }.start();

        //发送获取用户收藏量请求子线程
        new Thread() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                BufferedReader bufferedReader = null;
                String data = "";
                try {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 3;//增加handlerMsg标识符

                    URL url = new URL(Tool.InetAddress + "/getUcollNum.do");//请求地址
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //连接类相关设置
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(3000);//连接服务器超时
                    connection.setReadTimeout(3000);//从服务器读取数据超时
                    connection.setDoInput(true);//允许写入，从服务端读取结果流
                    connection.setDoOutput(true);//允许写出，开启Post请求体
                    connection.setUseCaches(false);//不使用Cache
                    connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                    connection.connect();//连接网络
                    String params = "UID=" + visitorUID;//请求体内容
                    outputStream = connection.getOutputStream();//请求输出流
                    outputStream.write(params.getBytes());

                    int code = connection.getResponseCode();//获得响应状态码
                    if (code == 200) {//返回状态码200，连接成功
                        bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        data = bufferedReader.readLine();

                        handlerMsg.obj = data;//写入线程传递消息
                    } else handlerMsg.obj = "serverFalse";//服务器通信失败
                    connection.disconnect();//关闭连接

                    handler.sendMessage(handlerMsg);//发送线程消息
                } catch (IOException e) {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 3;//增加handlerMsg标识符
                    handlerMsg.obj = "serverFalse";
                    handler.sendMessage(handlerMsg);

                    //throw new RuntimeException(e);
                } finally {
                    try {
                        if (bufferedReader != null) bufferedReader.close();
                        if (outputStream != null) {
                            outputStream.flush();
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        System.out.println("子线程：finally失败");
                        //throw new RuntimeException(e);
                    }
                }
            }
        }.start();

        //发送访客空间查询所有贴文列表请求子线程
        new Thread() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                BufferedReader bufferedReader = null;
                String data = "";
                try {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 4;//增加handlerMsg标识符

                    URL url = new URL(Tool.InetAddress + "/searchAllPerSubArtListVisitor.do");//请求地址
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //连接类相关设置
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(5000);//连接服务器超时
                    connection.setReadTimeout(5000);//从服务器读取数据超时
                    connection.setDoInput(true);//允许写入，从服务端读取结果流
                    connection.setDoOutput(true);//允许写出，开启Post请求体
                    connection.setUseCaches(false);//不使用Cache
                    connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                    connection.connect();//连接网络
                    String params = "UID=" + visitorUID;//请求体内容
                    outputStream = connection.getOutputStream();//请求输出流
                    outputStream.write(params.getBytes());

                    int code = connection.getResponseCode();//获得响应状态码
                    if (code == 200) {//返回状态码200，连接成功
                        bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        data = bufferedReader.readLine();

                        handlerMsg.obj = data;//写入线程传递消息
                    } else handlerMsg.obj = "serverFalse";//服务器通信失败
                    connection.disconnect();//关闭连接

                    handler.sendMessage(handlerMsg);//发送线程消息
                } catch (IOException e) {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 4;//增加handlerMsg标识符
                    handlerMsg.obj = "serverFalse";
                    handler.sendMessage(handlerMsg);

                    //throw new RuntimeException(e);
                } finally {
                    try {
                        if (bufferedReader != null) bufferedReader.close();
                        if (outputStream != null) {
                            outputStream.flush();
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        System.out.println("子线程：finally失败");
                        //throw new RuntimeException(e);
                    }
                }
            }
        }.start();

        //点赞列表文本监听事件
        linearLayoutVisitorFavorList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转活动，带有whatArtList、visitorUID参数
                Intent intent = new Intent(VisitorActivity.this, PersonArtListActivity.class);
                intent.putExtra("whatArtList", "favorList");
                intent.putExtra("UID", visitorUID);
                startActivity(intent);
                overridePendingTransition(R.anim.fade_out,R.anim.fade_in);//改变跳转活动动画，淡出淡入
            }
        });

        //收藏列表文本监听事件
        linearLayoutVisitorCollList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转活动，带有whatArtList、visitorUID参数
                Intent intent = new Intent(VisitorActivity.this,PersonArtListActivity.class);
                intent.putExtra("whatArtList", "collList");
                intent.putExtra("UID", visitorUID);
                startActivity(intent);
                overridePendingTransition(R.anim.fade_out,R.anim.fade_in);//改变跳转活动动画，淡出淡入
            }
        });

        //RecyclerView滚动监听事件
        recyclerViewVisitorArtList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                //滚动到底部时
                if (!recyclerView.canScrollVertically(1)) {
                    //showToast(Tool.addEmoji() + "已到达底部！");

                    //发送分页下一页请求子线程
                    new Thread() {
                        @Override
                        public void run() {
                            BufferedReader bufferedReader = null;
                            String data = "";
                            try {
                                Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                                handlerMsg.what = 5;//增加handlerMsg标识符

                                URL url = new URL(Tool.InetAddress + "/nextArticleListPage.do");//请求地址
                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                                //连接类相关设置
                                connection.setRequestMethod("POST");
                                connection.setConnectTimeout(5000);//连接服务器超时
                                connection.setReadTimeout(5000);//从服务器读取数据超时
                                connection.setDoInput(true);//允许写入，从服务端读取结果流
                                connection.setDoOutput(true);//允许写出，开启Post请求体
                                connection.setUseCaches(false);//不使用Cache
                                connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                                connection.connect();//连接网络

                                int code = connection.getResponseCode();//获得响应状态码
                                if (code == 200) {//返回状态码200，连接成功
                                    bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                                    data = bufferedReader.readLine();

                                    handlerMsg.obj = data;//写入线程传递消息
                                } else handlerMsg.obj = "serverFalse";//服务器通信失败
                                connection.disconnect();//关闭连接

                                handler.sendMessage(handlerMsg);//发送线程消息
                            } catch (IOException e) {
                                Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                                handlerMsg.what = 5;//增加handlerMsg标识符
                                handlerMsg.obj = "serverFalse";
                                handler.sendMessage(handlerMsg);

                                //throw new RuntimeException(e);
                            } finally {
                                try {
                                    if (bufferedReader != null) bufferedReader.close();
                                } catch (IOException e) {
                                    System.out.println("子线程：finally失败");
                                    //throw new RuntimeException(e);
                                }
                            }
                        }
                    }.start();
                }
            }
        });

        //悬浮按钮监听事件
        floatingActionButtonVisitorArtList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recyclerViewVisitorArtList.smoothScrollToPosition(0);//平滑滚动到顶部
            }
        });
    }

    //设置RecyclerView
    private void setRecyclerView(String artListData) {
        articleLists = new ArrayList<>();
        //解析JSON字符串
        try {
            JSONArray jsonArray = new JSONArray(artListData);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if (jsonObject.getString("artStatus").equals("1")) {
                    articleLists.add(
                            new ArticleList(
                                    Integer.parseInt(jsonObject.getString("artID")),
                                    jsonObject.getString("uname"),
                                    jsonObject.getString("artCategory"),
                                    jsonObject.getString("artTitle"),
                                    Integer.parseInt(jsonObject.getString("artFavorNum")),
                                    Integer.parseInt(jsonObject.getString("artCollNum")),
                                    Integer.parseInt(jsonObject.getString("artComNum")),
                                    jsonObject.getString("artSubTime"),
                                    -2
                            )
                    );
                }
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

        if (articleLists.size() > 0) showToast(Tool.addEmoji() + "已请求到数据，正在加载！");
        else showToast(Tool.addEmoji() + "没有贴文！");

        visitorArtListRecyclerAdapter = new PersonArtListRecyclerAdapter(this, this, articleLists);//构造Recycler适配器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);//创建线性布局管理器,默认子项布局垂直方向
        linearLayoutManager.setReverseLayout(false);//子项布局从顶部开始排列
        recyclerViewVisitorArtList.setLayoutManager(linearLayoutManager);//为RecyclerView设置布局管理器
        recyclerViewVisitorArtList.setAdapter(visitorArtListRecyclerAdapter);//为RecyclerView设置适配器
    }

    //动态增加RecyclerView子项
    private void addRecyclerViewItem(String addArtListData) {
        List<ArticleList> addArticleLists = new ArrayList<>();//增加的贴文列表
        //解析JSON字符串
        try {
            JSONArray jsonArray = new JSONArray(addArtListData);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if (jsonObject.getString("artStatus").equals("1")) {
                    addArticleLists.add(
                            new ArticleList(
                                    Integer.parseInt(jsonObject.getString("artID")),
                                    jsonObject.getString("uname"),
                                    jsonObject.getString("artCategory"),
                                    jsonObject.getString("artTitle"),
                                    Integer.parseInt(jsonObject.getString("artFavorNum")),
                                    Integer.parseInt(jsonObject.getString("artCollNum")),
                                    Integer.parseInt(jsonObject.getString("artComNum")),
                                    jsonObject.getString("artSubTime"),
                                    -2
                            )
                    );
                }
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

        articleLists.addAll(addArticleLists);
        if (addArticleLists.size() > 0) showToast(Tool.addEmoji() + "正在加载更多！");
        else showToast(Tool.addEmoji() + "已全部加载完成！");

        //动态增加RecyclerView子项
        visitorArtListRecyclerAdapter.notifyItemRangeInserted(articleLists.size() - addArticleLists.size(), addArticleLists.size());
    }

    //Toast消息提示框显示方法
    private void showToast(String s) {
        if (toast == null){
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }else {
            toast.cancel();
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }
        toast.show();
    }
}
